package com.jyh.service.Impl;




import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jyh.datasource.TargetDataSource;
import com.jyh.entity.Student;
import com.jyh.entity.StudentExample;
import com.jyh.mapper.StudentMapper;
import com.jyh.service.IStudentService;

import tk.mybatis.mapper.entity.Example;

/**
 * Student Service
 *
 * @author   单红宇(365384722)
 * @myblog  http://blog.csdn.net/catoop/
 * @create    2016年1月12日
 */
@Service("studentService")
@Transactional
public class StudentService implements IStudentService {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private StudentMapper studentMapper;
	
	/* (non-Javadoc)
	 * @see com.jyh.service.IStudentService#likeName(java.lang.String)
	 */
	@Override
//	@TargetDataSource(name="ds1")
	public List<Student> likeName(String name){
		StudentExample example = new StudentExample();
		example.createCriteria().andNameEqualTo(name);
		return studentMapper.selectByExample(example);
	}
	
	/* (non-Javadoc)
	 * @see com.jyh.service.IStudentService#testSave()
	 */
	@Override
	public int testSave(){
		Student stu = new Student();
		stu.setAge(33);
		stu.setName("测试新增");
		return studentMapper.insert(stu);
	}
	
	/**
	 * 事物回滚测试
	 */
	@Override
	@Transactional
	public List<Student> likeNameByDefaultDataSource(String name){
		StudentExample example = new StudentExample();
		example.createCriteria().andNameEqualTo(name);
		Student stu = new Student();
		stu.setAge(20);
		stu.setName("莉莉");
		studentMapper.insert(stu);
		if(name.equals("ERROR"))
			throw new RuntimeException("测试事务异常回滚");
		return studentMapper.selectByExample(example);
	}
	
	/**
	 * 手动sql查询
	 */
	@Override
	public List<Student> getList(){
		String sql = "select id,name,score_sum,score_avg, age   from student";
		return (List<Student>) jdbcTemplate.query(sql, new RowMapper<Student>(){

			@Override
			public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
				Student stu = new Student();
				stu.setId(rs.getInt("ID"));
				stu.setAge(rs.getInt("AGE"));
				stu.setName(rs.getString("NAME"));
				return stu;
			}
			
		});
	}
	
}
